package cn.heyige.backend.service.impl;

import cn.heyige.backend.entity.DivinationSettingDO;
import cn.heyige.backend.mapper.SettingsMapper;
import cn.heyige.backend.service.SettingsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@RequiredArgsConstructor
@Slf4j
public class SettingsServiceImpl implements SettingsService {
    
    private final SettingsMapper settingsMapper;
    
    @Override
    public Optional<DivinationSettingDO> getSettingsByUserId(Integer userId) {
        try {
            return settingsMapper.findByUserId(userId);
        } catch (Exception e) {
            log.error("根据用户ID获取占卜设置失败: {}", userId, e);
            return Optional.empty();
        }
    }
    
    @Override
    public DivinationSettingDO saveSettings(DivinationSettingDO settings) {
        try {
            // 检查是否已存在该用户的设置
            Optional<DivinationSettingDO> existingSettings = settingsMapper.findByUserId(settings.getUserId());
            
            if (existingSettings.isPresent()) {
                // 更新现有设置
                settings.setId(existingSettings.get().getId());
                settingsMapper.updateById(settings);
            } else {
                // 插入新设置
                settingsMapper.insert(settings);
            }
            
            return settings;
        } catch (Exception e) {
            log.error("保存占卜设置失败: {}", settings, e);
            return null;
        }
    }
    
    @Override
    public boolean deleteSettingsByUserId(Integer userId) {
        try {
            settingsMapper.deleteByUserId(userId);
            return true;
        } catch (Exception e) {
            log.error("删除用户占卜设置失败: {}", userId, e);
            return false;
        }
    }
}